<template>
  <div class="page-container">
    <!-- 待排车、待用车 -->
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical" v-if="orderStatus == 'notStarted'">
      <!-- 订单基础信息 -->
      <card title="客户信息">
        <a-alert class="a-alert">
          <template #icon>
            <icon-exclamation-circle />
          </template>
          <div class="alert-item">如承租人姓名或联系电话有误需要修改，请到个人会员中修改，或创建完成后，在订单编辑页中进行修改</div>
        </a-alert>
        <customer ref="customerRef" mode="editOrder" />
      </card>
      <card title="租赁信息">
        <lease mode="editOrder" ref="leaseRef" @timeRangeChange="timeRangeChange" />
      </card>
      <card title="订单排车" :showDivider="false">
        <platoon />
      </card>
    </page-form>
    <!-- 用车中、已还车、已完成 -->
    <template v-if="orderStatus == 'orderInProgress' || orderStatus == 'orderCompleted'">
      <!-- 顶部总结信息 -->
      <edit-summary-info :rules="rules" :orderDetail="orderDetail" @toggle="toggleSummaryInfoFn">
        <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
          <card title="客户信息">
            <customer ref="customerRef" mode="editOrder" />
          </card>
        </page-form>
        <!-- 租赁信息和订单排车不允许修改 -->
        <!-- 租赁信息用车中还车门店和上门取车地址支持修改 -->
        <page-form :model="form" :rules="rules" layout="vertical">
          <card title="租赁信息">
            <lease
              ref="leaseRef"
              :isProgress="orderStatus == 'orderInProgress' || orderStatus == 'orderCompleted'"
              mode="editOrder"
              @timeRangeChange="timeRangeChange"
            />
          </card>
        </page-form>
        <page-form :model="form" :rules="rules" layout="vertical" :disabled="true">
          <card title="订单排车" :showDivider="false">
            <platoon />
          </card>
        </page-form>
      </edit-summary-info>
      <!-- 交还车信息 -->
      <page-form :model="form" ref="formOrderCarInfoRef" layout="vertical" :rules="rules">
        <card title="交车信息" :showDivider="orderStatus == 'orderInProgress' ? false : true">
          <page-form-row>
            <page-form-item label="交车里程">
              <i-input-number :precision="0" unit="公里" v-model="form.giveCarMileage" />
            </page-form-item>
            <page-form-item label="交车油(电)量">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.giveFuelAmount" />
            </page-form-item>
            <page-form-item field="giveStaffId" label="交车人">
              <remote-select
                v-model="form.giveStaffId"
                :params="{
                  id: form.giveStaffId,
                  siteId: orderInfo.siteId,
                }"
                type="store_staff_bysite"
                :disabled="orderStaffCanClick(orderInfo, 'staff')"
              />
            </page-form-item>
            <page-form-item field="giveCarTime" label="交车时间">
              <i-date-picker class="w-full" v-model="form.giveCarTime" showTime />
            </page-form-item>
            <page-form-item label="交车备注" size="2/3">
              <i-textarea v-model="form.useStartRemark" />
            </page-form-item>
            <page-form-item label="交车照片" size="1">
              <upload-img v-model="form.giveFileIds" />
            </page-form-item>
            <page-form-item label="交车视频" size="1" class="mb-0">
              <upload-video v-model="form.giveVideoFileIds" :max="1" />
            </page-form-item>
          </page-form-row>
        </card>

        <card title="还车信息" :showDivider="false" v-if="orderStatus == 'orderCompleted'">
          <page-form-row>
            <page-form-item label="还车里程">
              <i-input-number :precision="0" unit="公里" v-model="form.returnCarMileage" />
            </page-form-item>
            <page-form-item label="还车油(电)量">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.returnFuelNum" />
            </page-form-item>
            <page-form-item field="returnStaffId" label="还车人">
              <remote-select
                v-model="form.returnStaffId"
                :params="{
                  id: form.returnStaffId,
                  siteId: orderInfo.returnSiteId,
                }"
                type="store_staff_list"
                :disabled="orderStaffCanClick(orderInfo, 'returnStaff')"
              />
            </page-form-item>
            <page-form-item field="returnCarTime" label="还车时间">
              <i-date-picker
                :allow-clear="false"
                class="w-full"
                v-model="form.returnCarTime"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:00"
                :time-picker-props="{
                  format: 'HH:mm',
                  defaultValue: '00:00',
                }"
                showTime
              />
            </page-form-item>
            <page-form-item label="还车备注" size="2/3">
              <i-textarea v-model="form.useEndRemark" />
            </page-form-item>
            <page-form-item label="还车照片" size="1">
              <upload-img v-model="form.returnFileIds" />
            </page-form-item>
            <page-form-item label="还车视频" size="1" class="mb-0">
              <upload-video v-model="form.returnVideoFileIds" :max="1" />
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
    </template>
  </div>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  <!-- 排车周期校验 -->
  <PlatoonCarCheckModal ref="platoonCarCheckModalRef" />
</template>

<script setup name="LongOrderEdit">
  import { ref, provide, nextTick, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { getCarHousekeepDetail } from '@/api/business/workorder'
  // 组件
  import customer from './components/customer.vue'
  import lease from './components/lease.vue'
  import platoon from './components/platoon.vue'
  import editSummaryInfo from './components/edit/edit-summary-info.vue'
  import { handleContracList } from '../utils'
  import { Notification } from '@arco-design/web-vue'
  import { getLongOrderDetails, modifyOrder, computeRentDay } from '@/api/order/czsOrder'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import { Modal } from '@arco-design/web-vue'
  // ---------------------------
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import useNavigate from '@/hooks/useNavigate'
  const { navigateBack } = useNavigate()
  const dict = usePageDict('longOrderDict')
  provide('dict', dict)

  const route = useRoute()
  const orderId = route.params.id

  // 表单对象
  const form = ref({
    timeRange: [],
    contractList: [
      {
        contractFileId: '',
        contractNo: '',
        contractType: 1,
        contractTypeName: '租赁合同',
        id: 1,
        refId: '',
        status: 'edit',
      },
    ],
  })
  provide('form', form)

  // formRef
  const formRef = ref()
  provide('formRef', formRef)

  // 订单详情
  const orderDetail = ref({})
  const orderInfo = ref({})
  provide('orderInfo', orderInfo)

  // 订单状态别名
  const orderStatus = ref('') // 'notStarted' | 'orderInProgress' | 'orderCompleted'
  // 获取订单详情
  getLongOrderDetails({ id: orderId }).then(({ result }) => {
    orderDetail.value = result
    orderInfo.value = result.orderInfo
    // 待排车 | 待交车
    if ([10, 100].includes(orderInfo.value.status)) orderStatus.value = 'notStarted'
    // 用车中
    if ([200].includes(orderInfo.value.status)) orderStatus.value = 'orderInProgress'
    // 已还车、已完成
    if ([300, 1000].includes(orderInfo.value.status)) orderStatus.value = 'orderCompleted'
    initFormValue()
    updateLeaseStore()
    handleOrderCarInfos()
  })

  /**
   * 是否开启车管家模式
   * 是：判断是否可以指派交/还车人，指派交/还车人后
   * 判断是否交还车人是否接受
   * @param {any} record
   * @param {any} type
   */
  const orderStaffCanClick = (record, type) => {
    const {
      orderSource,
      isCarHouseKeepOpen,
      assignGiveCarStaffFlag, // 是否可以修改交车人 1-可以修改 0-不可以修改
      assignReturnCarStaffFlag, // 是否可以修改还车人 1-可以修改 0-不可以修改
      channelOrderMaintenance, // 渠道订单维护方式 1-自动 2-手动
      status,
      inProgressGiveWorkOrderFlag, // 交车工单是否进行中 1-进行中 0-未进行中
      inProgressReturnWorkOrderFlag, // 还车工单是否进行中 1-进行中 0-未进行中
    } = record

    if (isCarHouseKeepOpen === 1) {
      // 修改交车人
      if (type === 'staff' && assignGiveCarStaffFlag === 1) {
        // 线下订单、渠道订单-手动
        if (orderSource === 1 || (orderSource === 2 && channelOrderMaintenance === 2)) {
          if ([200, 300, 1000].includes(status)) {
            return true
          }
        }

        // 渠道订单-自动
        if (orderSource === 2 && channelOrderMaintenance === 1) {
          if ([200, 300, 1000].includes(status)) {
            return false
          }
        }
      }

      // 修改还成人
      if (type === 'returnStaff' && assignReturnCarStaffFlag === 1) {
        // 线下订单、渠道订单-手动
        if (orderSource === 1 || (orderSource === 2 && channelOrderMaintenance === 2)) {
          if ([200, 300, 1000].includes(status)) {
            return true
          }
        }

        // 渠道订单-自动
        if (orderSource === 2 && channelOrderMaintenance === 1) {
          if ([300, 1000].includes(status)) {
            return false
          }
        }
      }

      return true
    } else {
      if (type === 'staff') {
        return assignGiveCarStaffFlag === 0 || inProgressGiveWorkOrderFlag === 1
      }

      if (type === 'returnStaff') {
        return assignReturnCarStaffFlag === 0 || inProgressReturnWorkOrderFlag === 1
      }
    }
  }

  // 处理订单交还车信息
  const handleOrderCarInfos = () => {
    const orderInfoVal = orderInfo.value
    const longOrderCarInfoDtos = orderInfoVal.longOrderCarInfoDtos
    if (longOrderCarInfoDtos?.length > 0) {
      // 用车中
      if (orderStatus.value == 'orderInProgress' || orderStatus.value == 'orderCompleted') {
        let carInfo = longOrderCarInfoDtos[0]
        form.value = {
          ...form.value,
          giveCarMileage: carInfo.giveCarMileage ? +carInfo.giveCarMileage : null,
          giveFuelAmount: carInfo.giveFuelAmount ? +carInfo.giveFuelAmount : null,
          giveStaffId: carInfo.giveStaffId,
          giveCarTime: carInfo.giveCarTime,
          useStartRemark: carInfo.remark,
          giveFileIds: carInfo.giveFileIds,
          giveVideoFileIds: carInfo.giveVideoFileIds,
        }
      }
      // 已还车、已完成
      if (orderStatus.value == 'orderCompleted') {
        let carInfo = longOrderCarInfoDtos[longOrderCarInfoDtos.length - 1]
        form.value = {
          ...form.value,
          returnCarMileage: carInfo.returnCarMileage,
          returnFuelNum: carInfo.returnFuelNum,
          returnStaffId: carInfo.returnStaffId,
          returnCarTime: carInfo.returnCarTime,
          useEndRemark: carInfo.useEndRemark,
          returnFileIds: carInfo.returnFileIds,
          returnVideoFileIds: carInfo.returnVideoFileIds,
        }
      }
    }
  }
  // 展开收起租赁信息
  const toggleSummaryInfoFn = (status) => {
    if (status) {
      const { memberInfoDto, orderInfo } = orderDetail.value
      if (customerRef.value) {
        customerRef.value.updateUploadDriverBtnStatus(!form.value.driverFrontFileId || !form.value.driverReverseFileId)
        // 更新显示上传身份证明按钮
        customerRef.value.updateUploadIdCardBtnStatus(
          !form.value.idCardFrontFileId || (form.value.cardType == 0 && !form.value.idCardReverseFileId)
        )
        customerRef.value.updateMemberInfo(memberInfoDto)
      }
      if (leaseRef.value) {
        if (orderInfo.address) {
          leaseRef.value.updateLnglatPickerTips('address')
        }
        if (orderInfo.returnAddress) {
          leaseRef.value.updateLnglatPickerTips('returnAddress')
        }
      }
      updateLeaseStore()
    } else {
      initFormValue()
    }
  }

  const platoonCarCheckModalRef = ref()
  const timeRangeChange = (val) => {
    platoonCarCheckModalRef.value.confirm({
      title: '预计租赁周期变更，不影响租车费及账单计划分期，请到订单详情-费用信息页面修改费用及账单分期，请确认是否修改预计租赁周期？',
      required: true,
      params: {
        refId: form.value.id,
        startTime: val[0] + ' 00:00:00',
        endTime: val[1] + ' 23:59:59',
        useType: 3,
        carId: form.value.carId,
      },
      onCancel: () => {
        let orderInfo = orderDetail.value.orderInfo || {}
        form.value.expectedUseCarTime = orderInfo.expectedUseCarTime
        form.value.expectedReturnCarTime = orderInfo.expectedReturnCarTime
        form.value.timeRange = [orderInfo.expectedUseCarTime, orderInfo.expectedReturnCarTime]
        form.value.rentDays = orderInfo.leaseNumberStr
        form.value.leaseNumberStr = orderInfo.leaseNumberStr
      },
    })
  }

  // 初始化 formValue
  const leaseRef = ref()
  const customerRef = ref()
  const initFormValue = () => {
    const { memberInfoDto, orderInfo } = orderDetail.value
    form.value = {
      ...form.value,
      id: orderId,
      // 会员相关信息
      clientId: orderInfo.clientId,
      memberId: orderInfo.memberId,
      memberName: orderInfo.memberName,
      memberPhone: orderInfo.memberPhone,
      cardType: memberInfoDto.cardType || 0,
      cardNumber: memberInfoDto.cardNumber,
      cardAddress: memberInfoDto.cardAddress,
      // 驾驶证正反面信息
      driverFrontFileId: memberInfoDto?.driverFrontFileId,
      driverReverseFileId: memberInfoDto?.driverReverseFileId,
      // 身份证明正反面信息
      idCardFrontFileId: memberInfoDto?.idCardFrontFileId,
      idCardReverseFileId: memberInfoDto?.idCardReverseFileId,
      // 紧急联系人信息
      emergencyContactName: memberInfoDto?.emergencyContactName,
      emergencyContactPhone: memberInfoDto?.emergencyContactPhone,
      // 订单相关信息
      orderSource: orderInfo.orderSource,
      orderAcquisitionType: orderInfo.orderAcquisitionType,
      // 客户类型
      memberType: orderInfo.memberType,
      // 渠道类型
      channelType: orderInfo.channelType,
      // 租期
      expectedUseCarTime: orderInfo.expectedUseCarTime,
      expectedReturnCarTime: orderInfo.expectedReturnCarTime,
      timeRange: [orderInfo.expectedUseCarTime, orderInfo.expectedReturnCarTime],
      rentDays: orderInfo.leaseNumberStr,
      leaseNumberStr: orderInfo.leaseNumberStr,
      // 门店
      siteId: orderInfo.siteId,
      returnSiteId: orderInfo.returnSiteId,
      address: orderInfo.address,
      longitude: orderInfo.longitude,
      latitude: orderInfo.latitude,
      returnAddress: orderInfo.returnAddress,
      returnLongitude: orderInfo.returnLongitude,
      returnLatitude: orderInfo.returnLatitude,
      sendServiceFlag: orderInfo.sendServiceFlag == 1 ? true : false,
      returnServiceFlag: orderInfo.returnServiceFlag == 1 ? true : false,
      // 车辆
      carId: orderInfo.carId,
      licenseNo: orderInfo.licenseNo,
      carSource: orderInfo.carSource,
      // 排车车型
      carModelId: orderInfo.modelId,
      carModelName: orderInfo.modelName,
      // 下单车型
      originalModelId: orderInfo.originalModelId,
      originalModelName: orderInfo.originalModelName,
      // 备注
      remark: orderInfo.remark,
      // 状态
      statusName: orderInfo.statusName,
      // 合同
      contractList: orderInfo.contractList,
    }
    // 合同信息处理
    if (orderInfo.contractList) {
      form.value.contractList = handleContracList(orderInfo.contractList)
    }
    nextTick(() => {
      if (customerRef.value) {
        customerRef.value.updateUploadDriverBtnStatus(!form.value.driverFrontFileId || !form.value.driverReverseFileId)
        // 更新显示上传身份证明按钮
        customerRef.value.updateUploadIdCardBtnStatus(
          !form.value.idCardFrontFileId || (form.value.cardType == 0 && !form.value.idCardReverseFileId)
        )
        customerRef.value.updateMemberInfo(memberInfoDto)
      }
      if (leaseRef.value) {
        if (orderInfo.address) {
          leaseRef.value.updateLnglatPickerTips('address')
        }
        if (orderInfo.returnAddress) {
          leaseRef.value.updateLnglatPickerTips('returnAddress')
        }
      }
    })
  }
  // 更新门店取送车开关逻辑
  const updateLeaseStore = () => {
    nextTick(() => {
      const { orderInfo } = orderDetail.value
      // 更新取还车门店是否显示
      if (leaseRef.value) {
        if (orderInfo.siteId == orderInfo.returnSiteId) {
          leaseRef.value.updateLongsiteConfig(orderInfo.siteId, ['site', 'returnSite'])
        } else {
          // 更新取车门店
          leaseRef.value.updateLongsiteConfig(orderInfo.siteId, ['site'])
          // 更新还车门店
          leaseRef.value.updateLongsiteConfig(orderInfo.returnSiteId, ['returnSite'])
        }
      }
    })
  }

  // 租赁周期限制最小时长 1个月
  const timeRangeValidator = async (value, callback) => {
    if (value) {
      let start = value[0]
      let end = value[1]
      const param = {
        expectedUseCarTime: dayjs(start).format('YYYY-MM-DD 00:00:00'),
        expectedReturnCarTime: dayjs(end).format('YYYY-MM-DD 23:59:59'),
      }
      let res = await computeRentDay(param)
      if (res.result.months < 1) {
        callback('租赁周期最短时间范围为1个月')
      }
    }
    callback()
  }
  // 表单规则
  const rules = {
    memberType: { required: true, message: '请选择客户类型' },
    memberPhone: [
      { required: true, message: '请输入联系电话' },
      { match: /^[0-9]+$/, message: '仅支持数字' },
    ],
    memberName: { required: true, message: '请输入承租人' },
    cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文' },
    clientId: { required: true, message: '请选择客户公司名称' },
    siteId: { required: true, message: '请选择取车门店' },
    orderSource: { required: true, message: '请选择订单来源' },
    timeRange: [{ required: true, message: '请选择预计租赁周期' }, { validator: timeRangeValidator }],

    // 交还车
    giveStaffId: [{ required: true, message: '请选择交车人' }],
    giveCarTime: [{ required: true, message: '请选择交车时间' }],
    returnStaffId: [{ required: true, message: '请选择还车人' }],
    returnCarTime: [{ required: true, message: '请选择交车时间' }],
  }
  provide('rules', rules)

  // 确认事件
  const okLoading = ref(false)
  const formOrderCarInfoRef = ref()
  const submitFn = () => {
    new Promise((resolve) => {
      let validate = 0
      // 验证基础信息
      if (formRef.value) {
        formRef.value.validate((error) => {
          if (!error) {
            validate += 1
            if (validate == 2) resolve()
          }
        })
      } else {
        validate += 1
        if (validate == 2) resolve()
      }
      // 验证交还车信息
      if (formOrderCarInfoRef.value) {
        formOrderCarInfoRef.value.validate((error) => {
          if (!error) {
            validate += 1
            if (validate == 2) resolve()
          }
        })
      } else {
        validate += 1
        if (validate == 2) resolve()
      }
    }).then(() => {
      console.log('验证通过')
      new Promise((resolve) => {
        // 判断租期是否发生变化
        let prevStartTime = orderInfo.value.startTime
        let prevEndTime = orderInfo.value.endTime
        let currStartTime = form.value.startTime
        let currEndTime = form.value.endTime
        if (prevStartTime != currStartTime || prevEndTime != currEndTime) {
          Modal.confirm({
            title: '确认',
            content: '预计租赁周期变更，租车费产生差异，请到订单详情-费用信息页修改费用信息，请确认是否修改？',
            okText: '确认',
            cancelText: '关闭',
            onOk: () => {
              resolve()
            },
          })
        } else {
          resolve()
        }
      }).then(() => {
        // 验证通过
        let param = {
          ...form.value,
          sendServiceFlag: form.value.sendServiceFlag ? 1 : 0,
          returnServiceFlag: form.value.returnServiceFlag ? 1 : 0,
        }
        // 获取 orderCarInfos
        const orderInfoVal = orderInfo.value
        const longOrderCarInfoDtos = orderInfoVal.longOrderCarInfoDtos
        if (longOrderCarInfoDtos.length > 0) {
          let firstCarInfo = longOrderCarInfoDtos[0]
          let lastCarInfo = longOrderCarInfoDtos[longOrderCarInfoDtos.length - 1]
          let orderCarInfos = []
          // 发生过交还车
          let giveCarInfo = {
            id: firstCarInfo.id,
            startCarMileage: form.value.giveCarMileage ? +form.value.giveCarMileage : null,
            startCarOil: form.value.giveFuelAmount ? +form.value.giveFuelAmount : null,
            giveStaffId: form.value.giveStaffId,
            useStartTime: form.value.giveCarTime,
            useStartRemark: form.value.useStartRemark,
            giveFileIds: form.value.giveFileIds,
            giveVideoFileIds: form.value.giveVideoFileIds,
          }
          // 已还车、已完成
          if (orderStatus.value == 'orderCompleted') {
            let returnCarInfo = {
              id: lastCarInfo.id,
              endCarMileage: form.value.returnCarMileage,
              endCarOil: form.value.returnFuelNum,
              returnStaffId: form.value.returnStaffId,
              useEndTime: form.value.returnCarTime,
              useEndRemark: form.value.useEndRemark,
              returnFileIds: form.value.returnFileIds,
              returnVideoFileIds: form.value.returnVideoFileIds,
            }
            if (firstCarInfo.id == lastCarInfo.id) {
              orderCarInfos = [
                {
                  ...giveCarInfo,
                  ...returnCarInfo,
                },
              ]
            } else {
              orderCarInfos = [giveCarInfo, returnCarInfo]
            }
          } else {
            orderCarInfos = [giveCarInfo]
          }
          param.orderCarInfos = orderCarInfos
        }
        if (form.value.emergencyContactPhone == '') {
          param.emergencyContactPhone = null
        }
        // 默认值
        let contractList = form.value.contractList
        param.contractFileId = contractList[0].contractFileId
        param.contractNo = contractList[0].contractNo
        param.contractName = contractList[0].contractName
        param.channelType = 0
        // 删除部分冗余字段
        delete param.rentDays
        delete param.timeRange
        // 开启 loading
        okLoading.value = true

        modifyOrder(param)
          .then(() => {
            Notification.success({
              content: '保存成功',
              closable: true,
              duration: 3000,
            })
            navigateBack()
          })
          .finally(() => {
            // 结束 loading
            okLoading.value = false
          })
      })
    })
  }

  // 车管家模式
  const carHousekeep = ref({
    isOpenCarHousekeep: 0,
  })
  // 获取车管家详情
  const getStaffDetail = () => {
    getCarHousekeepDetail().then((res) => {
      carHousekeep.value = res.result
    })
  }

  onMounted(() => {
    getStaffDetail()
  })
</script>

<style lang="less" scoped>
  .a-alert {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    margin-bottom: 20px;
  }
</style>
